#! /bin/bash
#
# VPN network Bring up/down networking
#
# chkconfig: 345 20 80
# description: Starts and stops the pptp network connections
#
# /etc/rc.d/init.d/oslo_vpn
# See how we were called.

DEVICE=ppp0

function vpn_conn(){
    nohup /usr/sbin/pppd call OSLO_VPN >/dev/null 2>&1 &
    sleep 5

    [ -r /var/run/$DEVICE.pid ] && route add -net 10.0.0.0 netmask 255.0.0.0 gw 10.101.0.167 device $DEVICE
    if [ $? -eq 0 ]
    then
        return 0
    else
        return 1
    fi
}

function vpn_dscn(){
    if [ -r /var/run/$DEVICE.pid ]
    then
        kill -INT `cat /var/run/$DEVICE.pid`
        if [ !"$?" = "0" ]
        then
            rm -rf /var/run/$DEVICE.pid
            # echo "ERROR: Removed stale pid file"
            return 1
        fi
        # echo "PPP link to $DEVICE terminated."
        return 0
    fi

    # echo "ERROR: PPP link is not active on $DEVICE"
    return 1
}


function ck_itf(){
  interface_test=$(ifconfig | grep "ppp0 ")
  if [ "$interface_test" != "" ]
  then
    #echo "[OK]: VPN interface exists"
    return 0
  else
    #echo "[ER]: VPN not found, reconnecting......"
    vpn_dscn
    vpn_conn
    return 1
  fi
}

function ck_link(){
  link_test=$(ping -c 3 10.0.0.1 | grep "time=")
  if [ "$link_test" != "" ]
  then
    #echo "[OK]: Gateway is online"
    return 0
  else
    #echo "[ER]: Gateway is offline, reconnecting......"
    vpn_dscn
    vpn_conn
    return 1
  fi
}

function vpn_proc_pid(){
  ps -elf | grep oslo_vpn | grep background | grep -v grep | awk '{print $4}' | head -n 1
}

case "$1" in
    start)
        nohup $0 background >/dev/null 2>&1 &
        sleep 3
        PID=`vpn_proc_pid`
        echo "Started oslo_vpn [$PID]"
        exit 0
    ;;

    stop)
        PID=`vpn_proc_pid`
        if [ "$PID" != "" ]
        then
            kill -s 9 $PID
            sleep 3
            vpn_dscn
            echo "Stopped oslo_vpn [$PID]"
        else
            echo "Nothing to do."
        fi
        exit 0
    ;;

    restart)
        $0 stop
        $0 start
        exit 0
    ;;

    status)
        PID=`vpn_proc_pid`
        [ "$PID" != "" ] && echo "OSLO_VPN Daemon Process [$PID]"
        [ -r /var/run/$DEVICE.pid ] && echo "OSLO_VPN PPTP Connect Process [`cat /var/run/$DEVICE.pid`]"
        ifconfig | grep "P-t-P:" | awk '{gsub(/^ */,"",$0);print "OSLO_VPN "$0;}'
        exit 0
    ;;

    background)
        while [ 1 ]
        do
            ck_itf
            sleep 10
            ck_link
            sleep 10
        done
        exit 0
    ;;

    *)
        echo "Usage: /etc/init.d/oslo_vpn {start|stop|restart|status}"
        exit 1
    ;;
esac


